import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { getOtp } from '@/apis/base/index';
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { message } from 'antd';
import module from './Login.module.scss';
import { useTimerStore, useUserStore } from '@/store/index';
import { loginApi, registerApi } from '@/apis/users';
import { useEffect } from 'react';

// 定义邮箱和手机号正则表达式
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const phoneRegex = /^(\+?\d{1,3}[- ]?)?\d{10}$/; // 这里假设为简单的手机号格式（如中国的11位手机号）

// 定义 Zod 验证规则
const formSchema = z.object({
  account: z
    .string()
    .min(1, '账号是必填项')
    .refine((value) => emailRegex.test(value) || phoneRegex.test(value), {
      message: '格式错误', // 当输入既不是邮箱也不是手机号时，显示此错误
    }),
  OTP: z.string().min(1, '验证码是必填项').length(6, '验证码格式错误'),
});
//检查是邮箱还是手机号
const checkType = (data: string) => {
  return data.match(emailRegex)
    ? 'email'
    : data.match(phoneRegex)
      ? 'phone'
      : '';
};
// interface FormState {
//   account: string;
//   OTP: string;
// }

export const LoginForm: React.FC = () => {
  const navigate = useNavigate();
  const { timer, beginTimer } = useTimerStore();
  const { changeToken } = useUserStore();
  const {
    register,
    handleSubmit,
    formState: { errors },
    getValues,
    setValue,
  } = useForm({
    resolver: zodResolver(formSchema),
  });
  const sendOtp = async (type: 'register' | 'login') => {
    const accountValue = getValues('account');
    const method = checkType(accountValue);
    if (!method) {
      message.error('请输入正确的邮箱或手机号');
      return;
    }

    beginTimer(); // 调用开始倒计时的函数

    const data = {
      way: type,
      target: accountValue,
      method: method as 'email' | 'phone',
    };
    console.log(data);
    const res = await getOtp(data);
    if (res.code === 200) {
      message.success('验证码已发送');
    }
  };
  const handleLoginSubmit = async (data: { account: string; OTP: string }) => {
    console.log(data);
    const method = checkType(data.account);
    if (!method) {
      message.error('请输入正确的邮箱或手机号');
      return;
    }
    const temp = {
      data: data.account,
      code: data.OTP,
      method: method as 'email' | 'phone',
    };
    const res = await loginApi(temp);
    if (res.code === 200) {
      message.success('登录成功');
      changeToken(res.data.token);
      setTimeout(() => {
        navigate('/home');
      }, 1000);
    } else {
      message.error(res.message || '登录失败');
    }
  };

  const handleSignUpSubmit = async (data: { account: string; OTP: string }) => {
    console.log(data);
    // 注册逻辑
    console.log(data);
    const method = checkType(data.account);
    if (!method) {
      message.error('请输入正确的邮箱或手机号');
      return;
    }
    const temp = {
      data: data.account,
      code: data.OTP,
      method: method as 'email' | 'phone',
    };
    const res = await registerApi(temp);
    console.log(res);
    if (res.code === 200) {
      message.success('注册成功');
      changeToken(res.data.token);
      setTimeout(() => {
        navigate('/home');
      }, 1000);
    } else {
      message.error(res.message || '注册失败');
    }
  };
  const clearForm = () => {
    // 清空表单
    console.log('clear form');
    setValue('account', '');
    setValue('OTP', '');
  };
  useEffect(() => {
    if (localStorage.getItem('timer')) {
      beginTimer();
    }
  }, []);
  return (
    <Card>
      <div className="mb-2 h-24 scale-75 cursor-default bg-[url('https://hire-sphere.oss-cn-shenzhen.aliyuncs.com/image/logo%402x.png')] bg-contain bg-center bg-no-repeat"></div>
      <Tabs
        defaultValue="sign-in"
        className="w-[400px]"
        onValueChange={clearForm}
      >
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="sign-in">登陆</TabsTrigger>
          <TabsTrigger value="sign-up">注册</TabsTrigger>
        </TabsList>
        <TabsContent value="sign-up">
          <Card>
            <CardHeader>
              <CardTitle>注册</CardTitle>
              <CardDescription>
                请使用未注册过的邮箱或者手机号进行注册
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-2">
              <div className="space-y-1">
                <Label htmlFor="account">账号</Label>
                <Input
                  id="account"
                  placeholder="请输入邮箱或者手机号"
                  {...register('account')}
                />
                {errors.account && (
                  <p className="text-sm text-red-500">
                    {errors.account.message}
                  </p>
                )}
              </div>
              <div className="space-y-1">
                <Label htmlFor="OTP">验证码</Label>
                <div className="flex w-full justify-between">
                  <div className="w-full">
                    <Input
                      id="OTP"
                      className="w-full"
                      placeholder="请输入验证码"
                      {...register('OTP')}
                    />
                    {errors.OTP && (
                      <p className="text-sm text-red-500">
                        {errors.OTP.message}
                      </p>
                    )}
                  </div>

                  <Button
                    className="ml-3"
                    variant="outline"
                    onClick={() => sendOtp('register')}
                    disabled={timer > 0}
                  >
                    {timer > 0 ? `${timer}秒后重发` : '发送'}
                  </Button>
                </div>
              </div>
            </CardContent>
            <CardFooter>
              <Button
                className={`float-right m-auto w-[70%] ${module.btnColor}`}
                onClick={handleSubmit(handleSignUpSubmit)}
              >
                注册
              </Button>
            </CardFooter>
          </Card>
        </TabsContent>
        <TabsContent value="sign-in">
          <Card>
            <CardHeader>
              <CardTitle>登陆</CardTitle>
              <CardDescription>
                请使用已注册过的邮箱或者手机号进行登录
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-2">
              <div className="space-y-1">
                <Label htmlFor="account">账号</Label>
                <Input
                  id="account"
                  type="text"
                  placeholder="请输入邮箱或手机号"
                  {...register('account')}
                />
                {errors.account && (
                  <p className="text-sm text-red-500">
                    {errors.account.message}
                  </p>
                )}
              </div>
              <div className="space-y-1">
                <Label htmlFor="OTP">验证码</Label>
                <div className="flex w-full justify-between">
                  <div className="w-full">
                    <Input
                      className="w-full"
                      id="OTP"
                      placeholder="请输入验证码"
                      {...register('OTP')}
                    />
                    {errors.OTP && (
                      <p className="text-sm text-red-500">
                        {errors.OTP.message}
                      </p>
                    )}
                  </div>
                  <Button
                    className="ml-3"
                    variant="outline"
                    onClick={() => sendOtp('login')}
                    disabled={timer > 0}
                  >
                    {timer > 0 ? `${timer}秒后重发` : '发送'}
                  </Button>
                </div>
              </div>
            </CardContent>
            <CardFooter>
              <Button
                className={`float-right m-auto w-[70%] ${module.btnColor}`}
                onClick={handleSubmit(handleLoginSubmit)}
              >
                登陆
              </Button>
            </CardFooter>
          </Card>
        </TabsContent>
      </Tabs>
    </Card>
  );
};
